<<<<<<< HEAD:项目代码/Backstage Management System/src/models/user.ts
import { login ,getQuestionType,getUserInfo,getViewAuthoritys} from '@/service';
=======
import { login ,getQuestionType,getUserInfo, getViewNew} from '@/service';
>>>>>>> 925273379b18744fc15f250871f012fa5f2db418:项目代码/liuexam_cms/src/models/user.ts
import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';
import {setToken, getToken} from '@/utils/cookie';
import menus from "../utils/menu"
import { IMenu } from '@/utils/interface';
let flag=false
export interface IndexModelState {
  userInfo: {[key:string]:any}
  isLogin:boolean,
  list:object[]
  userMenu:IMenu[],
}
export interface IndexModelType {
  namespace: 'user';
  state: IndexModelState;
  effects: {
    login: Effect;
    getList:Effect;
    getUserInfo:Effect;
    getViewAuthority:Effect;
  };
  reducers: {
    save: Reducer<IndexModelState>;
    // 启用 immer 之后
    // save: ImmerReducer<IndexModelState>;
  };
  subscriptions: { setup: Subscription };
}
const UserModel: IndexModelType = {
  namespace: 'user',
  state: {
    userInfo: {},
    isLogin:false,
    list:[],
    userMenu:[]
  },
  // 异步操作，理解为vuex中的action, async/await理解为generator函数的语法糖
  effects: {
    *login({payload}, {call, put}){
      let result = yield call(login, payload);
      if(result.token){
        setToken(result.token);
        // 存储token
        yield put({
          type: 'save',
          payload: {isLogin: true}
        })
      }
    },
    *getList({},{call,put}){
      let result= yield call(getQuestionType)
      yield put({
        type:"save",
        payload:{list:result.data}
      })
    },
    //用户信息
    *getUserInfo({ payload }, { call, put }) {
      let result = yield call(getUserInfo);
      if (result.data) {
        flag = true;
        // 存储用户信息
        yield put({
          type: 'save',
          payload: { userInfo: result.data }
        })
        yield put({
<<<<<<< HEAD:项目代码/Backstage Management System/src/models/user.ts
          type: 'getViewAuthority'
=======
          type: 'getViewAuthority',
          payload:{user_id:result.data.user_id}
>>>>>>> 925273379b18744fc15f250871f012fa5f2db418:项目代码/liuexam_cms/src/models/user.ts
        })
      }
    },
    *getViewAuthority({payload}, {call, put}) {
<<<<<<< HEAD:项目代码/Backstage Management System/src/models/user.ts
      let result = yield call(getViewAuthoritys);
=======
      let result = yield call(getViewNew,payload);
>>>>>>> 925273379b18744fc15f250871f012fa5f2db418:项目代码/liuexam_cms/src/models/user.ts
      // 处理用户拥有的视图数据
      let userMenu: IMenu[] = [];
      if (result.data){
        menus.forEach(item=>{
          let children = item.children.filter(value=>{
            return result.data.findIndex((view:any)=>{
              return view.view_id === value.meta.view_id;
            }) !== -1
          })
          if (children.length){
            userMenu.push({...item, children});
          }
        })
      }
      // 获取用户视图数据
      yield put({
        type: 'save',
        payload: { userMenu}
      })
    }
  },
  // 同步操作，理解为vuex中的mutation
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    }
    // 启用 immer 之后
    // save(state, action) {
    //   state.name = action.payload;
    // },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        let authorization = getToken();
        // 首页重定向
        if (pathname === '/') {
          history.replace('/main');
        }
        if (pathname === '/main') {
          history.replace('/main/addQuestion');
        }
        // 登录页重定向
        if (authorization){
          if (pathname === '/login'){
            history.replace('/main');
          }
        }else{
          if (pathname !== '/login'){
            history.replace(`/login?redirect=${encodeURIComponent(pathname)}`);
          }
        }
        if(!flag && authorization){
          dispatch({
            type: 'getUserInfo'
          })
        }
      });
     
    }

  }
};
export default UserModel;

